from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr

import smtplib

class SimpleEmail:
    """
    此类型实例表示一个简单的邮件发送工具。
    """

    def __init__(self):
        """
        初始化邮件发送工具。
        """
        self.smtp_server = 'smtp.sina.com'
        self.from_address = 'zhajiny@sina.com'
        self.password = 'dfd15378aafb3e48'

    def __format_address(self, s:str)-> str:
        """
        对邮件地址进行格式化处理。

        参数：
            要处理的邮件地址文本。
        """
        name, address = parseaddr(s)
        return formataddr((Header(name, 'utf-8').encode(), address))

    def send_html_email(self, to_address:str ,code:str, subject:str='无主题', debug_level=1)-> bool:
        """
        发送一封HTML类型的电子邮件。

        参数：
            to_address 邮件接收地址。
            code 邮件HTML格式内容。
            subject 邮件主题。
            debug_level 调试等级。默认值为1。
        """
        msg = MIMEText(code, 'html', 'utf-8')
        msg['From'] = self.__format_address(self.from_address)
        msg['To'] = self.__format_address(to_address)
        msg['Subject'] = Header(subject, 'utf-8').encode()
        try:
            server = smtplib.SMTP(self.smtp_server, 25)
            server.set_debuglevel(debug_level)
            server.login(self.from_address, self.password)
            server.sendmail(self.from_address, [to_address], msg.as_string())
            server.quit()
        except Exception as e:
            return False
        return True